package com.etoak.config.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.etoak.config.security.exception.CustomerAuthenionException;
import com.etoak.utils.ResultVo;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author by 孙有泽
 * @Date 2025/2/25 21:58
 * @Description
 */
@Component("loginFailureHanler")
public class LoginFailureHanler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        int code=500;
        String str="";
        if(e instanceof AccountExpiredException){
            str+="账号过期";
        }else if(e instanceof CredentialsExpiredException){
            str+="密码过期";
        } else if (e instanceof DisabledException) {
            str+="账号被禁用";
        } else if (e instanceof LockedException) {
            str+="账号被锁定";
        } else if (e instanceof InternalAuthenticationServiceException) {
            str+="认证服务异常";
        } else if (e instanceof CustomerAuthenionException) {
            code=600;
            str= e.getMessage();

        } else if (e instanceof InsufficientAuthenticationException) {
            str+="认证信息不足";
        }else {
            str+="用户名或密码错误";
        }
        String res= JSONObject.toJSONString(new ResultVo<>(code,str,null), SerializerFeature.DisableCircularReferenceDetect);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(res.getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();

    }
}
